<template>
  <div class="china-map-container">
    <div class="map-controls">
      <el-button @click="clearConnections" type="warning">清除连接</el-button>
      <div class="info-text">点击两个省份进行连接</div>
    </div>

    <div ref="mapContainer" class="map-wrapper"></div>

    <div class="map-info">
      <div class="info-title">统计信息</div>
      <div class="info-content">
        <div class="info-item">
          <span class="info-label">总人口：</span>
          <span class="info-value">{{ formatNumber(totalPopulation) }} 万人</span>
        </div>
        <div class="info-item" v-if="selectedProvinces.length > 0">
          <span class="info-label">已选省份：</span>
          <span class="info-value">{{ selectedProvinces.map(p => p.name).join(', ') }}</span>
        </div>
        <div class="info-item" v-if="connections.length > 0">
          <span class="info-label">连接数：</span>
          <span class="info-value">{{ connections.length }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import * as echarts from 'echarts'

const mapContainer = ref(null)
let chart = null

const selectedProvinces = ref([])
const connections = ref([])
const totalPopulation = ref(0)

// 省份数据 - 包含完整坐标信息
const provinceData = [
  { name: '北京', value: 2189, coords: [116.4, 39.9] },
  { name: '天津', value: 1386, coords: [117.2, 39.1] },
  { name: '河北', value: 7556, coords: [114.5, 38.0] },
  { name: '山西', value: 3718, coords: [112.5, 37.8] },
  { name: '内蒙古', value: 2520, coords: [111.7, 40.8] },
  { name: '辽宁', value: 4359, coords: [123.4, 41.8] },
  { name: '吉林', value: 2407, coords: [125.3, 43.8] },
  { name: '黑龙江', value: 3773, coords: [126.6, 45.7] },
  { name: '上海', value: 2487, coords: [121.4, 31.2] },
  { name: '江苏', value: 8505, coords: [118.7, 32.0] },
  { name: '浙江', value: 6540, coords: [120.1, 30.2] },
  { name: '安徽', value: 6127, coords: [117.2, 31.8] },
  { name: '福建', value: 4188, coords: [119.3, 26.0] },
  { name: '江西', value: 4519, coords: [115.8, 28.6] },
  { name: '山东', value: 10170, coords: [117.0, 36.6] },
  { name: '河南', value: 9883, coords: [113.6, 34.7] },
  { name: '湖北', value: 5927, coords: [114.3, 30.5] },
  { name: '湖南', value: 6644, coords: [112.9, 28.2] },
  { name: '广东', value: 12684, coords: [113.2, 23.1] },
  { name: '广西', value: 5037, coords: [108.3, 22.8] },
  { name: '海南', value: 1008, coords: [110.3, 20.0] },
  { name: '重庆', value: 3205, coords: [106.5, 29.5] },
  { name: '四川', value: 8375, coords: [104.0, 30.6] },
  { name: '贵州', value: 3856, coords: [106.7, 26.5] },
  { name: '云南', value: 4721, coords: [102.7, 25.0] },
  { name: '西藏', value: 365, coords: [91.1, 29.6] },
  { name: '陕西', value: 3954, coords: [108.9, 34.2] },
  { name: '甘肃', value: 2502, coords: [103.8, 36.0] },
  { name: '青海', value: 594, coords: [101.7, 36.6] },
  { name: '宁夏', value: 728, coords: [106.2, 38.4] },
  { name: '新疆', value: 2585, coords: [87.6, 43.8] }
]

// 飞机SVG图标
const airplaneIcon = 'path://M1705.06,1318.313v-89.254l-319.9-221.799l0.073-208.063c0.521-84.662-26.629-121.796-63.961-121.491c-37.332-0.305-64.482,36.829-63.961,121.491l0.073,208.063l-319.9,221.799v89.254l330.343-157.288l12.238,241.308l-134.449,92.931l0.531,42.034l175.125-42.917l175.125,42.917l0.531-42.034l-134.449-92.931l12.238-241.308L1705.06,1318.313z'

// 格式化数字
const formatNumber = (num) => {
  return num.toLocaleString()
}

// 初始化地图
const initMap = () => {
  if (!mapContainer.value) return

  chart = echarts.init(mapContainer.value)
  updateMapData()

  window.addEventListener('resize', handleResize)
}

// 更新地图数据
const updateMapData = () => {
  if (!chart) return

  totalPopulation.value = provinceData.reduce((sum, item) => sum + item.value, 0)

  // 构建系列数据
  const series = [
    {
      name: '人口分布',
      type: 'scatter',
      symbolSize: (data) => {
        return Math.sqrt(data[2]) / 4 + 8
      },
      itemStyle: {
        color: (params) => {
          const value = params.data[2]
          if (value > 5000) return '#1565C0'
          if (value > 2000) return '#2E9EE5'
          if (value > 1000) return '#7BC2F1'
          if (value > 500) return '#B8E0F7'
          return '#E8F4FD'
        },
        borderColor: '#fff',
        borderWidth: 2
      },
      label: {
        show: true,
        position: 'top',
        formatter: (params) => {
          return `${params.data[3]}\n${params.data[2]}万人`
        },
        fontSize: 10,
        color: '#333',
        fontWeight: 'bold'
      },
      emphasis: {
        itemStyle: {
          shadowBlur: 15,
          shadowColor: 'rgba(0, 0, 0, 0.3)',
          borderColor: '#FF6B35',
          borderWidth: 3
        }
      },
      data: provinceData.map(item => [
        item.coords[0],
        item.coords[1],
        item.value,
        item.name
      ])
    }
  ]

  // 添加连接线
  connections.value.forEach((conn, index) => {
    console.log(`处理连接 ${index}:`, conn)

    // 验证连接数据完整性
    if (!conn || !conn.from || !conn.to) {
      console.error('连接数据不完整:', conn)
      return
    }

    // 通过省份名称重新查找完整的省份数据
    const fromProvince = provinceData.find(p => p.name === conn.from.name)
    const toProvince = provinceData.find(p => p.name === conn.to.name)

    if (!fromProvince) {
      console.error('未找到起始省份:', conn.from.name)
      return
    }

    if (!toProvince) {
      console.error('未找到目标省份:', conn.to.name)
      return
    }

    console.log('找到省份对象:', {
      from: fromProvince,
      to: toProvince
    })

    // 计算调整后的起点和终点，使连接线从省份边缘开始
    const calculateAdjustedPoint = (from, to) => {
      try {
        const dx = to.coords[0] - from.coords[0]
        const dy = to.coords[1] - from.coords[1]
        const distance = Math.sqrt(dx * dx + dy * dy)

        console.log('计算连接线调整:', {
          from: from.name,
          to: to.name,
          fromCoords: from.coords,
          toCoords: to.coords,
          distance: distance
        })

        // 如果两点重合，直接返回原始坐标
        if (distance === 0 || isNaN(distance) || !isFinite(distance)) {
          console.log('距离为0或无效，使用原始坐标')
          return {
            adjustedStart: [...from.coords],
            adjustedEnd: [...to.coords]
          }
        }

        // 计算单位方向向量
        const unitX = dx / distance
        const unitY = dy / distance

        // 计算散点半径
        const fromValue = from.value || 1000
        const toValue = to.value || 1000
        const fromRadius = (Math.sqrt(fromValue) / 4 + 8) * 0.5
        const toRadius = (Math.sqrt(toValue) / 4 + 8) * 0.5

        console.log('计算半径:', { fromValue, toValue, fromRadius, toRadius })

        // 根据散点大小调整起点和终点
        const adjustedStart = [
          from.coords[0] + unitX * fromRadius,
          from.coords[1] + unitY * fromRadius
        ]

        const adjustedEnd = [
          to.coords[0] - unitX * toRadius,
          to.coords[1] - unitY * toRadius
        ]

        console.log('调整后的坐标:', { adjustedStart, adjustedEnd })

        return { adjustedStart, adjustedEnd }
      } catch (error) {
        console.error('计算调整点时发生错误:', error)
        console.error('参数:', { from, to })
        // 返回原始坐标作为fallback
        return {
          adjustedStart: [...from.coords],
          adjustedEnd: [...to.coords]
        }
      }
    }

    const { adjustedStart, adjustedEnd } = calculateAdjustedPoint(fromProvince, toProvince)

    series.push({
      name: `连接线${index}`,
      type: 'lines',
      coordinateSystem: 'cartesian2d',
      zlevel: 2,
      effect: {
        show: true,
        period: 6,
        trailLength: 0.7,
        color: '#FF6B35',
        symbolSize: 10,
        symbol: airplaneIcon
      },
      lineStyle: {
        width: 3,
        opacity: 0.8,
        curveness: 0.2,
        color: '#FF6B35'
      },
      data: [{
        coords: [adjustedStart, adjustedEnd]
      }]
    })
  })

  // 添加选中省份标记
  selectedProvinces.value.forEach(province => {
    series.push({
      name: '选中省份',
      type: 'scatter',
      symbolSize: 25,
      itemStyle: {
        color: '#FF6B35',
        borderColor: '#fff',
        borderWidth: 3
      },
      zlevel: 5,
      data: [[province.coords[0], province.coords[1], province.value, province.name]]
    })
  })

  const option = {
    backgroundColor: '#F0F8FF',
    title: {
      text: '中国人口分布地图 - 点击省份进行连接',
      left: 'center',
      top: 20,
      textStyle: {
        fontSize: 20,
        fontWeight: 'bold',
        color: '#1565C0'
      }
    },
    tooltip: {
      trigger: 'item',
      formatter: (params) => {
        if (params.seriesType === 'scatter' && params.data) {
          return `${params.data[3]}<br/>人口：${formatNumber(params.data[2])} 万人<br/>点击选择进行连接`
        }
        return `${params.name}`
      }
    },
    grid: {
      left: '10%',
      right: '10%',
      bottom: '10%',
      top: '15%'
    },
    xAxis: {
      type: 'value',
      show: false,
      min: 70,
      max: 140
    },
    yAxis: {
      type: 'value',
      show: false,
      min: 15,
      max: 55
    },
    series: series
  }

  chart.setOption(option)

  // 点击事件
  chart.off('click')
  chart.on('click', (params) => {
    console.log('点击事件参数:', params)

    try {
      if (params.seriesType === 'scatter' && params.data && params.data[3]) {
        const provinceName = params.data[3]
        const provinceValue = params.data[2]
        const lng = params.data[0]
        const lat = params.data[1]

        console.log('省份点击数据:', {
          name: provinceName,
          value: provinceValue,
          lng: lng,
          lat: lat
        })

        handleProvinceClick(provinceName, provinceValue, lng, lat)
      }
    } catch (error) {
      console.error('处理省份点击时发生错误:', error)
      console.error('错误堆栈:', error.stack)
    }
  })
}

// 处理省份点击
const handleProvinceClick = (name, value, lng, lat) => {
  console.log('点击省份:', name, value, lng, lat)

  // 参数验证
  if (!name || typeof name !== 'string') {
    console.error('无效的省份名称:', name)
    return
  }

  // 查找省份对���
  const province = provinceData.find(p => p.name === name)
  if (!province) {
    console.error('未找到省份:', name)
    console.error('可用省份列表:', provinceData.map(p => p.name))
    return
  }

  // 验证省份数据完整性
  if (!province.coords || !Array.isArray(province.coords) || province.coords.length < 2) {
    console.error('省份坐标数据无效:', province.coords)
    return
  }

  // 检查是否已选中
  const existingIndex = selectedProvinces.value.findIndex(p => p.name === name)

  if (existingIndex !== -1) {
    // 取消选中
    selectedProvinces.value.splice(existingIndex, 1)
    console.log('取消选中:', name)
  } else {
    // 添加到选中列表
    selectedProvinces.value.push(province)
    console.log('选中:', name, '当前选中数量:', selectedProvinces.value.length)

    // 如果有两个选中省份，创建连接
    if (selectedProvinces.value.length === 2) {
      createConnection(selectedProvinces.value[0], selectedProvinces.value[1])
    }
  }

  updateMapData()
}

// 创建连接
const createConnection = (province1, province2) => {
  console.log('创建连接:', province1.name, '->', province2.name)
  console.log('省份1坐标:', province1.coords)
  console.log('省份2坐标:', province2.coords)

  connections.value.push({
    from: province1,
    to: province2
  })

  // 清空选中省份
  selectedProvinces.value = []

  updateMapData()
}

// 清除连接
const clearConnections = () => {
  connections.value = []
  selectedProvinces.value = []
  updateMapData()
}

// 处理窗口大小变化
const handleResize = () => {
  if (chart) {
    chart.resize()
  }
}

// 组件挂载时初始化
onMounted(() => {
  initMap()
})

// 组件卸载前清理
onBeforeUnmount(() => {
  if (chart) {
    chart.dispose()
  }
  window.removeEventListener('resize', handleResize)
})
</script>

<style scoped>
.china-map-container {
  width: 100%;
  height: 100vh;
  position: relative;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  overflow: hidden;
}

.china-map-container::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background:
    radial-gradient(circle at 20% 50%, rgba(120, 119, 198, 0.3) 0%, transparent 50%),
    radial-gradient(circle at 80% 80%, rgba(255, 182, 193, 0.3) 0%, transparent 50%);
  pointer-events: none;
}

.map-controls {
  position: absolute;
  top: 20px;
  left: 20px;
  z-index: 1000;
  display: flex;
  align-items: center;
  gap: 15px;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  padding: 15px 20px;
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.info-text {
  color: #666;
  font-size: 14px;
  font-weight: 500;
}

.map-wrapper {
  width: 100%;
  height: 100%;
  position: relative;
  z-index: 1;
}

.map-info {
  position: absolute;
  top: 20px;
  right: 20px;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  padding: 20px;
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  z-index: 1000;
  min-width: 240px;
}

.info-title {
  font-weight: bold;
  margin-bottom: 15px;
  color: #1565C0;
  font-size: 14px;
}

.info-content {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 5px 0;
  border-bottom: 1px solid rgba(0, 0, 0, 0.05);
}

.info-item:last-child {
  border-bottom: none;
}

.info-label {
  color: #666;
  font-size: 13px;
  font-weight: 500;
}

.info-value {
  color: #1565C0;
  font-weight: bold;
  font-size: 13px;
  text-align: right;
}

:deep(.el-button) {
  border-radius: 8px;
  font-weight: 500;
  transition: all 0.3s ease;
}

:deep(.el-button:hover) {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}
</style>